import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:ichinesereader/widgets/layouts/customAppBar.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/controller/cache.dart';

//直接使用webview的方式登录
class InAppWebViewIndividualSubscriptionScreen extends StatefulWidget {
  static const String routeName = '/individual/subscription';
  @override
  _InAppWebViewIndividualSubscriptionScreenState createState() =>
      new _InAppWebViewIndividualSubscriptionScreenState();
}

class _InAppWebViewIndividualSubscriptionScreenState
    extends State<InAppWebViewIndividualSubscriptionScreen> {
  final GlobalKey webViewKey = GlobalKey();

  InAppWebViewController? webViewController;
  InAppWebViewSettings options = InAppWebViewSettings(
      useShouldOverrideUrlLoading: true,
      mediaPlaybackRequiresUserGesture: false,
      useHybridComposition: true,
      allowsInlineMediaPlayback: true,
      allowFileAccessFromFileURLs: true,
      allowUniversalAccessFromFileURLs: true,
      cacheEnabled: true,
      domStorageEnabled: true,
      javaScriptEnabled: true,
      allowsPictureInPictureMediaPlayback: true,
      enableViewportScale: true,
      disableLongPressContextMenuOnLinks: true,
      mixedContentMode: MixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW);

  late PullToRefreshController pullToRefreshController;
  late ContextMenu contextMenu;
  String url = "";
  String _authtoken = "";
  double progress = 0;
  final urlController = TextEditingController();
  final box = Hive.box('appconfig');
  // get the CookieManager instance
  CookieManager cookieManager = CookieManager.instance();
  final expiresDate =
      DateTime.now().add(Duration(days: 3)).millisecondsSinceEpoch;

  void loadautoken() async {
    await cookieManager.setCookie(
      url: WebUri.uri(Uri.parse(Constants.BaseURL)),
      name: "nanhaiV4.8Role",
      value: box.get(CacheManagerKey['nanhairole'].toString()) ?? '',
      domain: Constants.BaseDomain,
      path: '/',
      expiresDate: expiresDate,
      isSecure: true,
    );

    await cookieManager.setCookie(
      url: WebUri.uri(Uri.parse(Constants.BaseURL)),
      name: "nanhaiV4.8IndividualSession",
      value: box.get(CacheManagerKey['authtoken'].toString()) ?? '',
      domain: Constants.BaseDomain,
      path: '/',
      expiresDate: expiresDate,
      isSecure: true,
    );

    await cookieManager.setCookie(
      url: WebUri.uri(Uri.parse(Constants.BaseURL)),
      name: "nanhaiV4.8IndividualUserId",
      value: box.get(CacheManagerKey['username'].toString()) ?? '',
      domain: Constants.BaseDomain,
      path: '/',
      expiresDate: expiresDate,
      isSecure: true,
    );

    setState(() {
      _authtoken = box.get(CacheManagerKey['authtoken'].toString()) ?? '';
    });
  }

  @override
  void initState() {
    super.initState();

    loadautoken();

    pullToRefreshController = PullToRefreshController(
      onRefresh: () async {
        if (Platform.isAndroid) {
          webViewController?.reload();
        } else if (Platform.isIOS) {
          webViewController?.loadUrl(
              urlRequest: URLRequest(url: await webViewController?.getUrl()));
        }
      },
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: CustomAppBar(title: "Subscription".tr),
        body: SafeArea(
            child: Column(children: <Widget>[
          Expanded(
            child: Stack(
              children: [
                InAppWebView(
                  key: webViewKey,
                  initialUrlRequest: URLRequest(
                      url: WebUri.uri(Uri.parse(
                          "${Constants.BaseURL}icr/student/individual/subscription")),
                      headers: {'authtoken': _authtoken}),
                  initialSettings: options,
                  pullToRefreshController: pullToRefreshController,
                  onWebViewCreated: (controller) {
                    webViewController = controller;
                  },
                  onPermissionRequest: (controller, request) async {
                    return PermissionResponse(
                        resources: request.resources,
                        action: PermissionResponseAction.GRANT);
                  },
                  shouldOverrideUrlLoading:
                      (controller, navigationAction) async {
                    var uri = navigationAction.request.url!;

                    if (![
                      "http",
                      "https",
                      "file",
                      "chrome",
                      "data",
                      "javascript",
                      "about"
                    ].contains(uri.scheme)) {
                      if (await canLaunchUrl(uri)) {
                        // Launch the App
                        await launchUrl(
                          uri,
                        );
                        return NavigationActionPolicy.CANCEL;
                      }
                    }
                    return NavigationActionPolicy.ALLOW;
                  },
                  onLoadStop: (controller, url) async {
                    List<Cookie> cookies = await cookieManager.getCookies(
                        url: WebUri.uri(Uri.parse(Constants.BaseURL)));
                    cookies.forEach((cookie) {
                      Log.debug(cookie.name + " " + cookie.value);
                    });
                  },
                  onReceivedError: (controller, request, error) {
                    pullToRefreshController.endRefreshing();
                  },
                  onProgressChanged: (controller, progress) {
                    if (progress == 100) {
                      pullToRefreshController.endRefreshing();
                    }
                    setState(() {
                      this.progress = progress / 100;
                      urlController.text = this.url;
                    });
                  },
                  onUpdateVisitedHistory: (controller, url, androidIsReload) {
                    setState(() {
                      this.url = url.toString();
                      urlController.text = this.url;
                    });
                  },
                  onConsoleMessage: (controller, consoleMessage) {
                    Log.debug(consoleMessage);
                  },
                ),
                progress < 1.0
                    ? LinearProgressIndicator(value: progress)
                    : Container(),
              ],
            ),
          ),
        ])));
  }
}
